package com.petdog.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web MVC配置类
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    
    /**
     * 配置资源处理器
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 模型文件资源处理器
        registry.addResourceHandler("/models/**")
                .addResourceLocations("classpath:/models/");
        
        // 图片上传资源处理器 - 旧版本路径，保持兼容性
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:uploads/");
                
        // 图片上传资源处理器 - 根据配置文件的新路径
        // 与application-dev.properties中的spring.file.upload.access-url配置保持一致
        registry.addResourceHandler("/api/files/images/**")
                .addResourceLocations("file:upload/images/");
    }
    
    /**
     * 配置CORS跨域请求
     */
    @Bean
    public UrlBasedCorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        
        // 允许所有源
        config.addAllowedOriginPattern("*");
        // 允许所有请求头
        config.addAllowedHeader("*");
        // 允许所有HTTP方法
        config.addAllowedMethod("*");
        // 允许携带凭证
        config.setAllowCredentials(true);
        
        // 应用配置到所有路径
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}
